Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
Typescript asigna una variable de tipo múltiple que contiene OR ( | ) a una variable de tipo único

Tengo una variable que tiene tipo de número o cadena. ¿Cómo puedo asignar su valor a una variable que solo acepta números?

 const id:Record<string, string|number> = {name:3} let num: Record<string, number>; num = id; //Shows error here

Sé que puede haber soluciones alternativas de JavaScript como escribir una función de conversión, pero estoy aprendiendo Typescript y quiero saber si hay keywords o soluciones específicas de TypeScript que están destinadas a usarse en tales casos, as Record<string,number> . .. que puede lanzarlo, en lugar de escribir aserción

Aquí hay un enlace al código en el patio de juegos de TypeScript

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Parece que ya respondiste tu pregunta, puedes transmitir con la palabra clave as.

 num = id as number

Si quisiera ser elegante, podría verificar el tipo de identificación con typeof, así que algo como esto

 if (typeof id === 'number') { number = id }
about 4 years ago · Juan Pablo Isaza Report

0

Puede usar las funciones de aserción de TypeScript 3.7 para hacer cumplir las comprobaciones en el código que no eliminó el tipo incorrecto:

 const id:Record<string, string|number> = {name:"3"} let num: Record<string,string>; //the code logic safely leads to this line only if "id" contains a number value declare function isNumId(id: Record<string, string | number>): asserts id is Record<string, string>; isNumId(id); num = id; // No longer shows error here

Por supuesto, podría ser más sencillo simplemente decirle a TS que estamos seguros del tipo:

 num = id as Record<string, string>; // No longer shows error here
about 4 years ago · Juan Pablo Isaza Report

0

El enlace del patio de juegos de TypeScript es un poco diferente de lo que está en la pregunta:

 const id:Record<string, string|number> = {name:"3"} let num: Record<string,string>; //the code logic safely leads to this line only if "id" contains a number value num = id; //shows error here

Pero de todos modos, hay dos formas rápidas de lidiar con eso:

 //One solution: const id2:Record<string, string> | Record<string,number> = {name:"3"} let num2: Record<string,string>; num2 = id2; //Antoher solution: const id3:Record<string, string|number> = {name:"3"} let num3: Record<string,string>; num3 = id as Record<string,string>;

https://www.typescriptlang.org/play?#code/LAKAkAxg9gdgzgFwAQEsAmAuASgU2gJzQB5F8UYBzAGiVPIoB8YBXAWwCMd8A+JAXiQBvGAENWODACIAzJIC+oMABscyFqwxJcBYnUpU9FbgG5QigPTmEACxxJoaO0qgUUEWiIBmOJQE8kKiJocEgIUKHWKCFK5HawfqieSJLokvawCCLkISJI6pz4SABuIkrMOGbg6vyoaMZIlnDWUADuIVz4UIW2+BUglWCWAPIwdnBQZQgosBiKitDwyOgATNh4XboIZPq0W-S8DFrrhCR7+vlcvALCYhIy8ooqamyrRzqn29SGJmCK6ss1FamfogwbmACCMDCPVoE2YUxmAwWiFq0jW70MNEMTDYBSuQlE4iksgU4CeeTYaLeGw+9AMZyMwLA6mkgLQSBEIW0NMx33qlSAA

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!